package com.lzdongrui.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lzdongrui.common.constant.Constants;
import com.lzdongrui.common.core.domain.model.ClientLoginUser;
import com.lzdongrui.framework.security.config.ClientUsernamePasswordAuthenticationToken;
import com.lzdongrui.framework.web.service.ClientTokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.lzdongrui.common.core.domain.model.LoginUser;
import com.lzdongrui.common.utils.SecurityUtils;
import com.lzdongrui.common.utils.StringUtils;
import com.lzdongrui.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Value("${token.header}")
    private String header;

    @Value("${token.secret}")
    private String secret;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ClientTokenService clientTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        if (checkRequestIsClient(request)){
            ClientLoginUser loginUser= clientTokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                clientTokenService.verifyToken(loginUser);
                ClientUsernamePasswordAuthenticationToken authenticationToken=new ClientUsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }else {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        chain.doFilter(request, response);
    }

    /**
     *<p>
     *     判断当前请求是否为前端用户
     *</p>
     * @author huanghemao@lzdongrui.com
     * @date 2023-01-09 21:12
     * @param request
     * @return boolean
     */
    private boolean checkRequestIsClient(HttpServletRequest request){
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }else {
            return false;
        }
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        Object o = claims.get(Constants.LOGIN_SOURCE);
        return !(null==o || Constants.LOGIN_BACKSTAGE.equals(o.toString()));
    }
}
